/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Operations.Geometry;

import java.awt.image.BufferedImage;

/**
 *
 * @author littlechild
 */
public class Utilities {
    /**
     * @param image
     * @param x
     * @param y
     * @return
     *          the rgb value of the position (x,y).
     *          if (x,y) is out of bound, return value would be 0
     *          
     */
    static public int doubleLinearInterpolate(BufferedImage image, double x, double y) {
        //leftmost point
        int x0=(int)x;
        int y0=(int)y;
        //System.out.println(x+"  "+y);
        int rgbmask=0xffffff;
        //get rgb
        int rgb11,rgb12,rgb21,rgb22;
        rgb11=getFrom(image,x0, y0);
        rgb12=getFrom(image,x0+1, y0);
        rgb21=getFrom(image,x0, y0+1);
        rgb22=getFrom(image,x0+1, y0+1);
        double left;
        double right;
        //reduce to the scenario in [0,1]
        y=y-y0;     
        x=x-x0;
        // now x, y become the weight
        
        left=y*(((rgb21)>>>16)&0xff)+(1-y)*(((rgb11)>>>16)&0xff);
        right=y*((rgb22>>>16)&0xff)+(1-y)*(((rgb12)>>>16)&0xff);
        int red=(int)(0.5+x*right+(1-x)*left);
        
        left=y*(((rgb21)>>>8)&0xff)+(1-y)*(((rgb11)>>>8)&0xff);
        right=y*((rgb22>>>8)&0xff)+(1-y)*(((rgb12)>>>8)&0xff);
        int green=(int)(0.5+x*right+(1-x)*left);
        
        left=y*(((rgb21))&0xff)+(1-y)*(((rgb11))&0xff);
        right=y*((rgb22)&0xff)+(1-y)*(((rgb12))&0xff);
        int blue=(int)(0.5+x*right+(1-x)*left);
        
        return (red<<16)|(green<<8)|blue;
    } 
    static public double doubleLinearInterpolate( double a[][], double x, double y) {
        int x0=(int)x;
        int y0=(int)y;
        y=y-y0;
        x=x-x0;
        double left=y*(getFrom(a,x0,y0+1))+(1-y)*getFrom(a,x0,y0);
        double right=y*(getFrom(a,x0+1,y0+1))+(1-y)*(getFrom(a,x0+1,y0));
        return (1-x)*left+x*right;
    }
    static public int getFrom(BufferedImage image,int x,int y) {
        if(x<0)
            return getFrom(image,x+1,y);
        if(y<0)
            return getFrom(image,x,y+1);
        if(x>=image.getWidth())
            return getFrom(image,x-1,y);
        if(y>=image.getHeight())
            return getFrom(image,x,y-1);
        return image.getRGB(x, y);
    }
    static public double getFrom(double a[][],int x,int y) {
        if(x<0)
            return getFrom(a,x+1,y);
        if(y<0)
            return getFrom(a,x,y+1);
        if(x>=a.length)
            return getFrom(a,x-1,y);
        if(y>=a[0].length)
            return getFrom(a,x,y-1);
        return a[x][y];
    }
}
